package com.litchi.tutor.common.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
public class JwtUtil {

    public static void main(String[] args) {
        System.out.println(generate(1, DateUtil.date().offset(DateField.DAY_OF_MONTH, 1)));
        System.out.println(getId("eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJKZXJzZXktU2VjdXJpdHktQmFzaWMiLCJzdWIiOiIxIiwiZXhwIjoxNjI2MDA4NzcyLCJpYXQiOjE2MjU5MjIzNzJ9.arWl-hagLZ8xlfacXwUs-iSTjH3UVGIK68lEYMOYNPI"));
    }

    private static final String KEY = "1234qwer";

    public static String generate(Integer id, Date expiration) {
        if (id == null) {
            throw new NullPointerException("null id is illegal");
        }
        if (expiration == null) {
            throw new NullPointerException("null expiration is illegal");
        }
        return Jwts.builder()
                .setIssuer("Jersey-Security-Basic")
                .setSubject(id.toString())
                .setExpiration(expiration)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, KEY)
                .compact();
    }

    public static boolean verify(String token) {
        try {
            Jwts.parser().setSigningKey(KEY).parseClaimsJws(token.trim());
            return true;
        } catch (Exception e) {
            log.error("无效的token:{}", token);
            return false;
        }
    }

    public static Integer getId(String token) {
        if (verify(token)) {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(KEY).parseClaimsJws(token);
            return Convert.toInt(claimsJws.getBody().getSubject(), null);
        }
        return null;
    }
}